import axios from 'axios'
import getAuthToken from './dingtalk'
// import getPermission from './permission'

axios.defaults.timeout = 10000
axios.defaults.headers.common['Content-Type'] = 'application/json'
axios.defaults.headers.common['x-ums-app-id'] = '247ea4f1'
// axios.defaults.headers.common['Authorization'] = `Bearer ${window.AUTH_TOKEN}`

// // 添加请求拦截器
// axios.interceptors.request.use(
//   function (config) {
//     // 在发送请求之前做些什么
//     return config
//   },
//   function (error) {
//     // 对请求错误做些什么
//     return Promise.reject(error)
//   }
// )

// 添加响应拦截器
axios.interceptors.response.use(
  async function (response) {
    // 2xx 范围内的状态码都会触发该函数。
    // 对响应数据做点什么
    return response?.data
  },
  async function (error) {
    // 超出 2xx 范围的状态码都会触发该函数。
    // 对响应错误做点什么
    const {status, config, response} = error
    switch (status) {
      case 401:
        const token = await getAuthToken()
        if (token) {
          const authorization = `Bearer ${token}`
          axios.defaults.headers.common['Authorization'] = authorization
          // config.headers['Authorization'] = authorization
          return axios.request(config)
        } else {
          if (response) {
            showFailToast(
              response?.data?.error?.errorText || response?.data?.error?.message || '操作失败，请联系管理员'
            )
          }
          return Promise.reject(error)
        }
      default:
        if (response) {
          showFailToast(response?.data?.error?.errorText || response?.data?.error?.message || '操作失败，请联系管理员')
        }
        return Promise.reject(error)
    }
  }
)

export const get = (url, data, config) => {
  return axios.get(url, {params: data}, config)
}

export const post = (url, data, config) => {
  return axios.post(url, data, config)
}

export const put = (url, data, config) => {
  return axios.put(url, data, config)
}

export const del = (url, data, config) => {
  return axios.del(url, data, config)
}

export default axios
